package summary;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/5 22:28
 * https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
 */
public class Sword07 {

    static class TreeNode{
        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static Map<Integer, Integer> hash;

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        hash = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            //前提节点数字都不重复;
            hash.put(inorder[i], i);
        }
        return traversal(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private static TreeNode traversal(int[] preorder, int preorderBegin, int preorderEnd, int[] inorder, int inorderBegin, int inorderEnd) {
        if (preorderEnd < preorderBegin) {
            return null;
        } else if (preorderEnd == preorderBegin) {
            return new TreeNode(preorder[preorderBegin]);
        }
        int rootValue = preorder[preorderBegin];
        TreeNode root = new TreeNode(rootValue);
        //在中序遍历中确定root的位置
        int rootIndex = hash.get(rootValue);
        //左子树的节点数目
        int size_left = rootIndex - inorderBegin;
        root.left = traversal(preorder, preorderBegin + 1, preorderBegin + size_left,
                inorder, inorderBegin, rootIndex - 1);
        root.right = traversal(preorder, preorderBegin + size_left + 1, preorderEnd,
                inorder, rootIndex + 1, inorderEnd);
        return root;
    }

    public static void main(String[] args) {
        int[] preorder = {3,9,20,15,7};
        int[] inorder = {9,3,15,20,7};
        buildTree(preorder, inorder);
    }
}
